/**
 *  TextMash - simple IDE for Clojure
 *  
 *  Copyright (C) 2010 Aleksander Naszko
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package pl.olek.textmash.workspace;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import pl.olek.textmash.Support;

/**
 * 
 * @author anaszko
 *
 */
public class DialogBox {

	JComponent[] buttons;
	int result = -1;
	JFrame frame;
	JDialog dialog;
//	ComponentAdapter adapter;

//	private void synchronizeLocation() {
//		Point p = frame.getLocationOnScreen();
//		dialog.setLocation((p.x + (frame.getWidth() / 2))
//				- (dialog.getWidth() / 2), p.y + 60);
//	}

	private DialogBox(final JFrame frame, String title, String message,
			String[] buttonsStrings, int defaultAction, int focusedAction) {
		this.frame = frame;
//		frame.addComponentListener(adapter = new ComponentAdapter() {
//
//			@Override
//			public void componentMoved(ComponentEvent e) {
//				synchronizeLocation();
//
//			}
//
//		});

		StringBuilder msg = new StringBuilder("<html><font size=\"4\"><b>");
		msg.append(title.replaceAll("\n", "<br>"));
		msg.append("</b></font><br><br><font size=\"3\">");
		msg.append(message.replaceAll("\n", "<br>"));
		msg.append("</font></html>");

		buttons = new JComponent[buttonsStrings.length];

		for (int i = 0; i < buttonsStrings.length; ++i) {
			final int res = Support.getInstance().positionDialogButton(
					buttonsStrings.length, i);

			if (buttonsStrings[i].length() == 0) {
				buttons[res] = new JLabel("            ");
			} else {

				buttons[res] = new JButton(buttonsStrings[i]);
				final JButton c = (JButton) buttons[res];

				if (i == focusedAction) {

					c.addComponentListener(new ComponentAdapter() {

						@Override
						public void componentMoved(ComponentEvent e) {
							JDialog box = getDialog(e.getSource());
							box.addWindowFocusListener(new WindowAdapter() {
								@Override
								public void windowGainedFocus(WindowEvent e) {
									c.requestFocus();
								}
							});
						}
					});

					c.addHierarchyListener(new HierarchyListener() {

						@Override
						public void hierarchyChanged(HierarchyEvent e) {
							JDialog box = getDialog(((JButton) e.getSource())
									.getParent());
							if (box != null) {
								if (dialog == null) {
//									box.setUndecorated(true);
									box.getRootPane().putClientProperty("Window.style", "small");
//									box.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
									dialog = box;
									
									//dialog.setModal(false);
//									dialog
//											.addComponentListener(new ComponentAdapter() {
//
//												@Override
//												public void componentShown(
//														ComponentEvent e) {
//													synchronizeLocation();
//												}
//
//											});
								}
							}

						}
					});
				}
				final int r = i;
				c.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						result = r;
//						frame.removeComponentListener(adapter);
						getDialog(e.getSource()).dispose();
					}
				});
			}

		}

		JOptionPane.showOptionDialog(frame, msg.toString(), null,
				JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
				new ImageIcon(Support.getInstance().getResource(
						"pl/olek/textmash/icon64.png")), buttons, buttons[Support
						.getInstance().positionDialogButton(
								buttonsStrings.length, defaultAction)]);
	}

	private int getResult() {
		return result;
	}

	private static JDialog getDialog(Object obj) {
		Component cmp = (Component) obj;
		do {
			if (cmp instanceof JDialog) {
				return (JDialog) cmp;
			}
		} while ((cmp = cmp.getParent()) != null);
		return null;
	}

	public static int showDialogBox(JFrame frame, String title, String message,
			int focusedAction, int defaultAction, String... buttons) {
		DialogBox box = new DialogBox(frame, title, message, buttons,
				defaultAction, focusedAction);
		return box.getResult();
	}
	
	public static void showErrorBox(JFrame frame, String title, Throwable e) {
		
		ByteArrayOutputStream o = new ByteArrayOutputStream();
		PrintStream p = new PrintStream(o);
		e.printStackTrace(p);
		String msg = o.toString();
//		if (msg.length() > 1021) {
//			msg = msg.substring(0, 1021) + "...";
//		}
		p.close();
//		DialogBox.showDialogBox((JFrame)null, "Unexpected error has occured",
//				msg, 0, 0,
//			"OK");
		
		JButton b = new JButton("OK");
		b.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				getDialog(e.getSource()).dispose();	
			}
		});
		
		JPanel pa = new JPanel();
		pa.setLayout(new BorderLayout());
		
		StringBuilder tit = new StringBuilder("<html><font size=\"4\"><b>");
		tit.append(title.replaceAll("\n", "<br>"));
		tit.append("</b></font><br><br></html>");
		
		
		JTextArea ta = new JTextArea(msg);
//		ta.setOpaque(true);
		
		JScrollPane sp = new JScrollPane(ta);
		sp.setPreferredSize(new Dimension(480, 240));
//		sp.setOpaque(true);
		ta.setCaretPosition(0);
		ta.setTabSize(2);
		ta.setFont(sp.getFont());
		pa.add(sp, BorderLayout.CENTER);
		pa.add(new JLabel(tit.toString()), BorderLayout.NORTH);
		JOptionPane.showOptionDialog(frame, pa, null,
				JOptionPane.OK_OPTION, JOptionPane.QUESTION_MESSAGE,
				new ImageIcon(Support.getInstance().getResource(
						"pl/olek/textmash/icon64.png")), new Object[] {
		b }, b);
	}
}
